package com.sunshine.lnuplus.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Environment
import android.view.animation.AlphaAnimation
import android.widget.ImageView
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.callback.LoadDataCallBack
import okhttp3.Response
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream


object BackgroundUtils {

    fun backgroundToFile(context: Context, response: Response, callBack: LoadDataCallBack){
        val backgroundSp = context.getSharedPreferences("background", Context.MODE_PRIVATE)
        val edit = backgroundSp.edit()

        val ist = response.body!!.byteStream()
        val file = File(context.filesDir.absolutePath + "/" + DateUtils.month + "-" + DateUtils.day + ".jpg")
        val fileOutputStream = FileOutputStream(file)
        var hasRead: Int
        while (ist.read().also { hasRead = it } != -1) {
            fileOutputStream.write(hasRead)
        }
        fileOutputStream.close()

        //删除之前下载的旧背景
        val oldPath = (context.filesDir.absolutePath + "/"
                + backgroundSp.getInt("month", 0) + "-" + backgroundSp.getInt("day", 0) + ".jpg")
        deleteFile(oldPath)

        edit.putInt("month", DateUtils.month)
        edit.putInt("day", DateUtils.day)
        edit.apply()
        callBack.onSuccess()
    }

    private fun deleteFile(filePath: String) {
        val file = File(filePath)
        if (file.isFile && file.exists()) {
            file.delete()
        }
    }

    fun setBackground(
        context: Context,
        backgroundEveryday: ImageView,
        last: Boolean,
        backgroundMohu: Int
    ) {
        val bitmap: Bitmap
        val getDate = context.getSharedPreferences("background", Context.MODE_PRIVATE)
        val backgroundFileName = (context.filesDir.absolutePath + "/"
                + getDate.getInt("month", 0) + "-" + getDate.getInt("day", 0) + ".jpg")
        var fis: FileInputStream? = null
        try {
            fis = FileInputStream(backgroundFileName)
        } catch (ignored: FileNotFoundException) {
        }
        if (fis != null) {
            bitmap = BitmapFactory.decodeStream(fis)
            backgroundEveryday.setImageBitmap(BlurBuilder.blur(
                context,
                bitmap,
                (backgroundMohu/100.0*25).toFloat()
            ))
            if(last){
                backgroundEveryday.alpha = 1.0f
            }else{
                val alphaAnimation = AlphaAnimation(0.0f, 1.0f)
                alphaAnimation.duration = 500
                backgroundEveryday.startAnimation(alphaAnimation)
            }
        }
    }

    fun toGetBackground(context: Context) : Boolean {
        val backgroundFileName = context.filesDir.absolutePath + "/" + DateUtils.month + "-" + DateUtils.day + ".jpg"
        return try {
            FileInputStream(backgroundFileName)
            false
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            true
        }
    }

    fun userBackgroundToFile(
        imageFile: File?,
        context: Context
    ): File? {
        var imageFile = imageFile
        try {
            if (imageFile != null && imageFile.exists()) {
                imageFile.delete()
            }
            imageFile =
                File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString() + "/userBackground.jpg")
            val fileOutputStream = FileOutputStream(imageFile)
            var hasRead: Int
            while (System.`in`.read().also { hasRead = it } != -1) {
                fileOutputStream.write(hasRead)
            }
            fileOutputStream.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return imageFile
    }

    fun setUserBackground(
        context: Context,
        background: ImageView,
        backgroundMohu: Int
    ): Boolean {
        val fileName =
            context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString() + "/userBackground.jpg"
        val bitmap: Bitmap
        return try {
            val fileInputStream = FileInputStream(fileName)
            bitmap = BitmapFactory.decodeStream(fileInputStream)
            background.setImageBitmap(BlurBuilder.blur(
                context,
                bitmap,
                (backgroundMohu/100.0*25).toFloat()
            ))
            true
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            false
        }
    }

    fun userImageToFile(imageFile: File?, context: Context): File? {
        var imageFile = imageFile
        try {
            if (imageFile != null && imageFile.exists()) {
                imageFile.delete()
            }
            imageFile =
                File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString() + "/userImage.jpg")
            val fileOutputStream = FileOutputStream(imageFile)
            var hasRead: Int
            while (System.`in`.read().also { hasRead = it } != -1) {
                fileOutputStream.write(hasRead)
            }
            fileOutputStream.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return imageFile
    }

    fun setUserImage(
        context: Context,
        user_image: ImageView
    ){
        val fileName =
            context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString() + "/userImage.jpg"
        val bitmap: Bitmap
        try {
            val fileInputStream = FileInputStream(fileName)
            bitmap = BitmapFactory.decodeStream(fileInputStream)
            val roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(context.resources, bitmap)
            roundedBitmapDrawable.isCircular = true
            user_image.setImageDrawable(roundedBitmapDrawable)
        } catch (e: Exception) {
            e.printStackTrace()
            val bitmap = BitmapFactory.decodeResource(context.resources, R.mipmap.background)
            val roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(context.resources, bitmap)
            roundedBitmapDrawable.isCircular = true
            user_image.setImageDrawable(roundedBitmapDrawable)
        }
    }

}